package hua.mtreader.feature.login.activity;

import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import hua.mtreader.R;
import hua.mtreader.base.BaseActivity;
import hua.mtreader.common.utils.ToastAlone;
import hua.mtreader.common.utils.ToolsPreferences;
import hua.mtreader.feature.login.bean.LoginRequestParam;
import hua.mtreader.feature.login.bean.UserBean;
import hua.mtreader.feature.login.present.LoginPresenter;
import hua.mtreader.feature.login.view.ILoginView;

public class LoginActivity extends BaseActivity<ILoginView,LoginPresenter> implements ILoginView {

    private final String TAG = getClass().getSimpleName();

    private EditText name;
    private EditText password;
    private Button loginBtn;
    private String mName;
    private String mPassword;
    private TelephonyManager tm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        assignViews();
        setListener();
        initData();
    }

    private void assignViews() {
        tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        name = (EditText) findViewById(R.id.name);
        password = (EditText) findViewById(R.id.password);
        loginBtn = (Button) findViewById(R.id.login_btn);
    }

    private void initData() {

    }



    @Override
    public LoginPresenter createPresenter() {
        return new LoginPresenter();
    }


    private void setListener() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    /**
     * 登录接口访问
     */
    private void login() {
        mName = name.getText().toString().trim();
        mPassword = password.getText().toString().trim();
        if (TextUtils.isEmpty(mName)) {
            ToastAlone.showShortToast("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(mPassword)) {
            ToastAlone.showShortToast("密码不能为空");
            return;
        }

        LoginRequestParam param = new LoginRequestParam();
        param.setEmail(new Pair<>("email", mName));
        param.setPassword(new Pair<>("password", mPassword));
        param.setDeviceId(new Pair<>("deviceId", tm.getDeviceId()));
        param.setUa(new Pair<>("ua", android.os.Build.MODEL));

        mPresenter.login(param);
    }

    @Override
    public void loginSuccess(UserBean user) {
        ToolsPreferences.persistenceUser(user);
        Log.e(TAG, "loginSuccess: user = " + user.toString());
        finish();
    }
}
